package com.captain.special.链表;

import com.captain.leetcode.链表.ListNode;

import java.util.List;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/3/22 9:24
 */
public class 删除链表的倒数第N个结点19 {
    //1 2 3 4 5
    public ListNode removeNthFromEnd(ListNode head, int n) {
        //前置链表,记录pre指针
        //一个链表先走n步, 当链表走到最后时,也就找到了要删除的节点
        ListNode dummy = new ListNode(-1, head);
        ListNode pre = dummy;
        //先让head先走n步
        for (int i = 0; i < n; i++) {
            head = head.next;
        }
        while (head != null) {
            pre = pre.next;
            head = head.next;
        }
        pre.next = pre.next.next;
        return dummy.next;
    }
}
